package com.marathon.ershor.textrecognizer;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by ershor on 2017/8/17.
 */

public class ImageDealer {

    public static byte[] readFile(File file) {
        int size = (int) file.length();
        byte[] bytes = new byte[size];
        try {
            BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
            buf.read(bytes, 0, bytes.length);
            buf.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return bytes;
    }
    private static final int BUFFER_SIZE = 1024 * 8;
    public static void writeBitmapToFile(Bitmap bitmap, File file) {
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            final BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
        }
    }
    public static File getOutputMediaFile(String fileName){
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/textrecognizer/Images");
        if (! mediaStorageDir.exists()){
            if (!mediaStorageDir.mkdirs()){
                return null;
            }
        }
        File mediaFile = new File(mediaStorageDir.getPath() + File.separator + fileName);
        return mediaFile;
    }

    public static Uri JpegDataToUri(byte[] data) {
        File file = getOutputMediaFile("origin.jpeg");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data);
            fos.close();
        } catch (IOException e) {
            Log.e("PictureDemo", "Exception in photoCallback", e);
        }
        return Uri.fromFile(file);
    }

    public static Bitmap getRotatedImagePath(String imagePath) {
        try {
            Bitmap bitmap = null;
            Bitmap bitmapPhoto = decodeSampledBitmapFromFile(imagePath, 2000, 2000);
            if (bitmapPhoto == null)
                return null;

            bitmap = Bitmap.createScaledBitmap(bitmapPhoto, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), true);
            ExifInterface exif = null;
            try {
                exif = new ExifInterface(imagePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

            orientation = 6; // gaochaohua: clockwise 90 degree
            Matrix matrix = new Matrix();
            if ((orientation == 3)) {
                matrix.postRotate(180);
                // matrix.postScale((float) bitmapPhoto.getWidth(),
                // (float)bitmapPhoto.getHeight());
                bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true);

            } else if (orientation == 6) {
                matrix.postRotate(90);
                // matrix.postScale((float) bitmapPhoto.getWidth(),
                // (float)bitmapPhoto.getHeight());
                bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true);

            } else if (orientation == 8) {
                matrix.postRotate(270);
                // matrix.postScale((float)
                // bitmapPhoto.getWidth(),(float)bitmapPhoto.getHeight());
                bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true);

            } else if (orientation == 1) {
                matrix.postRotate(90);
                // matrix.postScale((float)
                // bitmapPhoto.getWidth(),(float)bitmapPhoto.getHeight());
                bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0, bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix, true);
            }

            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            File myDirectory = new File(imagePath);
            if (!myDirectory.exists()) {
                myDirectory.mkdirs();
            }
            // String imgName = String.valueOf(System.currentTimeMillis()) +".jpg";
            File file = new File(imagePath);


            try {
                file.createNewFile();
                FileOutputStream fo = new FileOutputStream(file);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return bitmap;
        } catch (Exception e) {
            return null;
        }
    }

    private static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) {
        // BEST QUALITY MATCH
        try {
            //First decode with inJustDecodeBounds=true to check dimensions
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);

            // Calculate inSampleSize, Raw height and width of image
            final int height = options.outHeight;
            final int width = options.outWidth;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            int inSampleSize = 1;

            if (height > reqHeight) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            }
            int expectedWidth = width / inSampleSize;

            if (expectedWidth > reqWidth) {
                //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
            options.inSampleSize = inSampleSize;

            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeFile(path, options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
